﻿using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace TestApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int MaxDepth = 50;
        public MainWindow()
        {
            InitializeComponent();

            Loaded += MainWindow_Loaded;
            Window3 window3 = new Window3();
            window3.Show();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 初始化加载逻辑树和视觉树
            RefreshLogicalTree_Click(null, null);
            RefreshVisualTree_Click(null, null);
        }

        private void RefreshLogicalTree_Click(object sender, RoutedEventArgs e)
        {
            LogicalTreeView.Items.Clear();
            AddLogicalTree(this, LogicalTreeView.Items);
        }

        private void AddLogicalTree(DependencyObject parent, ItemCollection items, int depth = 0)
        {
            if (depth > MaxDepth)
                return;

            TreeViewItem item = new TreeViewItem { Header = parent.GetType().Name };
            items.Add(item);

            foreach (var child in LogicalTreeHelper.GetChildren(parent))
            {
                if (child is DependencyObject depObj && depObj != parent)
                {
                    AddLogicalTree(depObj, item.Items, depth + 1);
                }
            }
        }

        private void RefreshVisualTree_Click(object sender, RoutedEventArgs e)
        {
            // 清空现有树
            VisualTreeView.Items.Clear();

            // 获取根元素（窗口本身）
            Visual root = this;

            // 创建根节点
            TreeViewItem rootItem = CreateVisualTreeNode(root);
            VisualTreeView.Items.Add(rootItem);

            // 递归添加子节点
            AddVisualTreeChildren(root, rootItem);
        }

        private TreeViewItem CreateLogicalTreeNode(DependencyObject obj)
        {
            string nodeName = obj.GetType().Name;
            FrameworkElement fe = obj as FrameworkElement;
            if (fe != null && !string.IsNullOrEmpty(fe.Name))
            {
                nodeName += " (" + fe.Name + ")";
            }

            TreeViewItem item = new TreeViewItem
            {
                Header = nodeName,
                Tag = obj
            };

            return item;
        }

        private TreeViewItem CreateVisualTreeNode(Visual obj)
        {
            string nodeName = obj.GetType().Name;
            FrameworkElement fe = obj as FrameworkElement;
            if (fe != null && !string.IsNullOrEmpty(fe.Name))
            {
                nodeName += " (" + fe.Name + ")";
            }

            TreeViewItem item = new TreeViewItem
            {
                Header = nodeName,
                Tag = obj
            };

            return item;
        }

        private void AddLogicalTreeChildren(DependencyObject parent, TreeViewItem parentItem)
        {
            if (parent is Window || parent is AdornerDecorator)
                return;

            // 获取逻辑子元素
            IEnumerable logicalChildren = LogicalTreeHelper.GetChildren(parent);

            foreach (object child in logicalChildren)
            {
                if (child is DependencyObject childDO)
                {
                    TreeViewItem childItem = CreateLogicalTreeNode(childDO);
                    parentItem.Items.Add(childItem);

                    // 递归添加子节点
                    AddLogicalTreeChildren(childDO, childItem);
                }
            }
        }

        private void AddVisualTreeChildren(Visual parent, TreeViewItem parentItem)
        {
            // 获取视觉子元素
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                Visual child = VisualTreeHelper.GetChild(parent, i) as Visual;
                if (child != null)
                {
                    TreeViewItem childItem = CreateVisualTreeNode(child);
                    parentItem.Items.Add(childItem);

                    // 递归添加子节点
                    AddVisualTreeChildren(child, childItem);
                }
            }
        }

        private void ShowRenderingProcess_Click(object sender, RoutedEventArgs e)
        {
            // 创建一个演示渲染过程的动画
            Storyboard storyboard = new Storyboard();

            // 对示例UI区域中的所有元素添加动画
            foreach (var element in FindVisualChildren<UIElement>(this))
            {
                if (element is Button || element is TextBlock || element is TextBox || element is ListBox)
                {
                    // 透明度动画，模拟渲染过程
                    DoubleAnimation fadeInAnimation = new DoubleAnimation
                    {
                        From = 0.0,
                        To = 1.0,
                        Duration = TimeSpan.FromSeconds(0.5),
                        BeginTime = TimeSpan.FromSeconds(0.1 * (element.GetHashCode() % 10))
                    };

                    Storyboard.SetTarget(fadeInAnimation, element);
                    Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
                    storyboard.Children.Add(fadeInAnimation);

                    // 缩放动画，模拟元素定位
                    DoubleAnimation scaleAnimation = new DoubleAnimation
                    {
                        From = 0.8,
                        To = 1.0,
                        Duration = TimeSpan.FromSeconds(1),
                        BeginTime = TimeSpan.FromSeconds(0.1 * (element.GetHashCode() % 10))
                    };

                    element.RenderTransform = new ScaleTransform();
                    Storyboard.SetTarget(scaleAnimation, element);
                    Storyboard.SetTargetProperty(scaleAnimation, new PropertyPath("(UIElement.RenderTransform).(ScaleTransform.ScaleX)"));
                    storyboard.Children.Add(scaleAnimation);

                    DoubleAnimation scaleYAnimation = new DoubleAnimation
                    {
                        From = 0.8,
                        To = 1.0,
                        Duration = TimeSpan.FromSeconds(0.5),
                        BeginTime = TimeSpan.FromSeconds(0.1 * (element.GetHashCode() % 10))
                    };

                    Storyboard.SetTarget(scaleYAnimation, element);
                    Storyboard.SetTargetProperty(scaleYAnimation, new PropertyPath("(UIElement.RenderTransform).(ScaleTransform.ScaleY)"));
                    storyboard.Children.Add(scaleYAnimation);
                }
            }

            // 开始动画
            storyboard.Begin(this);
        }

        // 辅助方法：查找所有子元素
        private IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window1 window1 = new Window1();
            window1.ShowDialog();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Window2 window2 = new Window2();
            window2.Show();
        }
    }
}